package com.nurun.cacheimageloader.view;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.nurun.cacheimageloader.R;

public class CrossFadingImageView extends RelativeLayout {

    private String NEW_VIEW_TAG = "NEW_VIEW_TAG";
    private String OLD_VIEW_TAG = "OLD_VIEW_TAG";
    private String url = "";

    public CrossFadingImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void init() {
        findViewById(R.id.imageView1).setTag(NEW_VIEW_TAG);
        findViewById(R.id.imageView2).setTag(OLD_VIEW_TAG);
    }

    public ImageView getNewView() {
        return (ImageView) findViewWithTag(NEW_VIEW_TAG);
    }

    public ImageView getOldView() {
        return (ImageView) findViewWithTag(OLD_VIEW_TAG);
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void crossFade() {
        final long duration = 500;
        ImageView actualNewView = getNewView();
        ImageView actualOldView = getOldView();
        ObjectAnimator.ofFloat(actualNewView, "alpha", 0f, 1f).setDuration(duration).start();
        ObjectAnimator.ofFloat(actualOldView, "alpha", 1f, 0f).setDuration(duration).start();
        actualNewView.setTag(OLD_VIEW_TAG);
        actualOldView.setTag(NEW_VIEW_TAG);
    }

    public boolean isNotSameUrl(String url) {
        return !this.url.equals(url);
    }
}
